const core = require('@/xiluedu/core.js');
module.exports = {
  // 获取当前登录用户信息
  getUserinfo(forceLogin = false) {
      let userinfo = core.getCache('userinfo');
      if (!userinfo && forceLogin){
        uni.navigateTo({
          url: '/pages/login/login',
        });
        return false;
      }
      return userinfo;
  },
  setUserinfo(user) {
    if(!user) {
  	return false;
    }
    core.setCache('userinfo', user);
  },
  getCache(key, defaultValue) {
  	return core.getCache(key, defaultValue);
  },
  setCache(key, value, expireTimeInSeconds) {
      return core.setCache(key, value, expireTimeInSeconds);
  },
  removeCache(key) {
  	return core.removeCache(key);
  },
  //登出
  logout() {
	  core.removeCache('userinfo');
  },
   // 静默获取openid, 然后从服务器拉取wx_account信息
   wxLogin() {
	   let that = this;
      function executeLogin() {
        uni.login({
			provider: 'weixin',
			success: (auth) => {
			console.log(auth);
            let code = auth.code;
            core.post({
              url: 'xiluedu.user/wxlogin',
			  loading:false,
              data: {code: code},
              success: (ret, response) => {
                let third = ret.data.third;
                core.setCache('wx_account', third);
                if(third.binding == 1) that.setUserinfo(ret.data.userinfo);
              },fail: (ret, response) => {
                //失败，重试
                setTimeout(function(){
                  executeLogin();
                },60000);
                return false;
              }
            });
          },
        });
      }
      uni.checkSession({
		success(){
			executeLogin();
		},
        fail(){
          executeLogin();
        }
      });
    },
};
